<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body" v-if="cartList.length">
        <ul class="cart-list" v-for="item in cartList" :key="item.id">
          <li class="cart-list-con1">
            <input type="checkbox" :checked="item.isChecked === 1" name="chk_list" @click="changeStatus(item, $event)" />
          </li>
          <li class="cart-list-con2">
            <img :src="item.imgUrl" />
            <div class="item-msg">{{ item.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ item.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="changeTotal('sub', item, $event)">-</a>
            <input
              autocomplete="off"
              type="text"
              :value="item.skuNum"
              minnum="1"
              class="itxt"
              @change="changeTotal('input', item, $event)"
            />
            <a href="javascript:void(0)" class="plus" @click="changeTotal('add', item, $event)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">399</span>
          </li>
          <li class="cart-list-con7">
            <a href="javascript:;" class="sindelet" @click="delItem(item.skuId)">删除</a>
            <br />
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool" v-if="cartList.length">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" :checked="changeAllBox" @change="selectAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#none" @click="delAll">删除选中的商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ alreadyChecked }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
    <div class="empty" v-else>
      <h4>暂无想要购买的商品</h4>
      <img src="@/assets/datanot.gif" alt="" />
    </div>
  </div>
</template>

<script>
import { reqCart, reqChecked, batchCheckCart, deleteCart, batchDeleteCart } from '@/api/cart'
import { reqShopping } from '@/api/goodsdetail'
export default {
  name: 'ShopCart',
  // 组件导航守卫,进入组件之前
  // 如果不放行，就不能进入到该组件
  beforeRouteEnter(to, from, next) {
    console.log(to)
    console.log(from)
    next()
  },
  // 当腰离开盖组件的时候，如果不放行就不会离开
  beforeRouteLeave(to, from, next) {
    next()
  },
  data() {
    return {
      cartList: []
    }
  },
  async created() {
    const res = await reqCart()
    // console.log(res.data)
    if (res.data.length) {
      const [{ cartInfoList }] = res.data
      this.cartList = cartInfoList
    }
  },
  methods: {
    // 点击单选框
    async changeStatus(good, e) {
      // console.log(good, e.target.checked)
      // 获取商品id
      const id = good.skuId
      // 获取改变之后单选框的状态
      const status = e.target.checked ? 1 : 0
      // 发请求更改服务器的数据
      const res = await reqChecked(id, status)
      if (res.code === 200) {
        // 更改本地数据
        good.isChecked = status
      }
    },
    // 全选框
    async selectAll(e) {
      console.log(e.target.checked)
      // 拿全选框状态
      const isChecked = e.target.checked ? 1 : 0
      // 拿每一项商品的id组成数据
      const skuIdList = this.cartList.map((item) => item.skuId)
      // console.log(isChecked, skuIdList)
      // 根据全选框的状态更改每一项商品的状态，更改服务器的数据
      await batchCheckCart(isChecked, skuIdList)
      // 更改本地数据
      this.cartList.forEach((item) => {
        item.isChecked = isChecked
      })
    },
    // 点击删除单个
    async delItem(id) {
      // console.log(id)
      // if (confirm('确定要删除吗？')) {
      //   const res = await deleteCart(id)
      //   if (res.code === 200) {
      //     this.cartList = this.cartList.filter((item) => item.skuId === id)
      //   }
      // }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deleteCart(id)
          if (res.code === 200) {
            this.cartList = this.cartList.filter((item) => item.skuId !== id)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击删除全部选中按钮
    async delAll() {
      // 声明数组存储id
      const newArrList = []
      this.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          newArrList.push(item.skuId)
        }
      })
      // 发送请求更改后端的数据
      const res = await batchDeleteCart(newArrList)
      if (res.code === 200) {
        this.cartList = this.cartList.filter((item) => !newArrList.includes(item.skuId))
      }
    },
    // 数量框
    async changeTotal(type, good, e) {
      // console.log(type)
      // console.log(good, e)
      // 获取改变数量商品的id
      const { skuId, skuNum } = good
      if (type === 'input') {
        // 获取输入框的数量值
        const { value } = e.target
        // console.log(skuId, value, skuNum)
        // 判断输入框的数量是否合法
        const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
        const isReg = reg.test(value)
        // console.log(isReg)
        // 1.合法
        if (isReg) {
          // 计算出差值
          const diffNum = value - skuNum
          // 根据差值发送请求改变服务器的数据
          const res = await reqShopping(skuId, diffNum)
          if (res.code === 200) {
            good.skuNum = value * 1
            // 只要输入框数量发生更改，单选框就为选中状态
            // good.isChecked = 1
          } else {
            console.log('错了')
            // 发送请求失败的时候，输入值之后调回原本之前的值
            good.skuNum = e.target.value = skuNum
          }
          // 2.输入的数字大于200
        } else if (e.target.value > 200) {
          // 重新改变差值
          const diffNum = 200 - skuNum

          // 发送请求更改服务器的数据
          const res = await reqShopping(skuId, diffNum)
          if (res.code === 200) {
            // 设置输入框和data数据的值为200
            good.skuNum = e.target.value = 200
            good.isChecked = 1
          }
          // 输入的数字小于1
        } else {
          // 更改输入框和data的数据都为1
          good.skuNum = e.target.value = 1
          good.isChecked = 1
        }
        // 点击的是add的时候
      } else if (type === 'add') {
        // 当数据等于200的时候结束退出
        if (skuNum === 200) return
        // 发送请求
        // console.log('111')
        // 每次变化都是1 所以发请求的差值是1
        const res = await reqShopping(skuId, 1)
        if (res.code === 200) {
          // 当点击的时候改变data里面的数据为+1
          good.skuNum += 1
        }
        // 点击sub时候的逻辑
      } else if (type === 'sub') {
        // 等于1的时候直接退出
        if (skuNum === 1) return
        // 减法的时候每次差值是-1，所以用-1发送请求
        const res = await reqShopping(skuId, -1)
        if (res.code === 200) {
          good.skuNum -= 1
        }
      }
    }
  },
  computed: {
    // 当所有的都被选择了才改变全选框的状态
    changeAllBox() {
      return this.cartList.every((item) => item.isChecked)
    },
    // 已选中的商品个数
    alreadyChecked() {
      const length = this.cartList.filter((item) => item.isChecked === 1).length
      return length
    },
    // 总价格
    totalPrice() {
      let total = 0
      this.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          total += item.skuNum * item.skuPrice
        }
      })
      return total
    }
  }
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;
          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
.empty {
  text-align: center;
}
.empty img {
  width: 200px;
}
</style>
